// 定义接口返回数据的通用格式
export interface ApiResponse<T = any> {
  code: number; // 状态码，200表示成功
  message: string; // 消息描述
  data: T; // 响应数据
  [key: string]: any; // 其他可能的字段
}

// 定义分页响应数据格式
export interface PaginationData<T = any> {
  list: T[]; // 数据列表
  total: number; // 总条数
  pageNum: number; // 当前页码
  pageSize: number; // 每页条数
  [key: string]: any; // 其他可能的字段
}

// 定义分页请求参数格式
export interface PaginationParams {
  pageNum?: number; // 当前页码
  pageSize?: number; // 每页条数
  [key: string]: any; // 其他可能的查询参数
}

// 定义空响应数据格式
export interface EmptyResponse {
  // 空响应
}

// 检查是否是对象
export const isObject = (val: any): val is object => {
  return val !== null && typeof val === 'object';
};

// 深拷贝对象
export const deepClone = <T>(obj: T): T => {
  if (!isObject(obj)) {
    return obj;
  }
  
  if (obj instanceof Date) {
    return new Date(obj.getTime()) as unknown as T;
  }
  
  if (obj instanceof Array) {
    return obj.map((item) => deepClone(item)) as unknown as T;
  }
  
  const cloneObj: Record<string, any> = {};
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      cloneObj[key] = deepClone((obj as Record<string, any>)[key]);
    }
  }
  
  return cloneObj as T;
};

// 格式化日期
export const formatDate = (date: Date | string | number, format: string = 'YYYY-MM-DD HH:mm:ss'): string => {
  const d = new Date(date);
  
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  const hours = String(d.getHours()).padStart(2, '0');
  const minutes = String(d.getMinutes()).padStart(2, '0');
  const seconds = String(d.getSeconds()).padStart(2, '0');
  
  return format
    .replace('YYYY', year.toString())
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hours)
    .replace('mm', minutes)
    .replace('ss', seconds);
};

// 生成唯一ID
export const generateId = (): string => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2);
};

// 防抖函数
export const debounce = <T extends (...args: any[]) => any>(
  func: T,
  wait: number
): ((this: any, ...args: Parameters<T>) => void) => {
  let timeout: ReturnType<typeof setTimeout> | null = null;
  
  return function (this: any, ...args: Parameters<T>) {
    if (timeout) {
      clearTimeout(timeout);
    }
    
    timeout = setTimeout(() => {
      func.apply(this, args);
    }, wait);
  };
};

// 节流函数
export const throttle = <T extends (...args: any[]) => any>(
  func: T,
  wait: number
): ((this: any, ...args: Parameters<T>) => void) => {
  let previous = 0;
  
  return function (this: any, ...args: Parameters<T>) {
    const now = Date.now();
    if (now - previous > wait) {
      func.apply(this, args);
      previous = now;
    }
  };
};